//
//  NewFeatureCollectionViewController.swift
//  TWeibo
//
//  Created by wtw on 15/7/31.
//  Copyright © 2015年 wtw. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class NewFeatureCollectionViewController: UICollectionViewController {

    //图像总数
    private let imageCount = 4
    
     private let layout = NewFeatureLayOut()
    
    init() {
        super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //注册重用cell
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    /// 数据源方法
    //获取数据源，确认有cell
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageCount
    }
    //获取每个索引对应的cell
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell
        
        // Configure the cell
        cell.imageIndex = indexPath.item
        
        return cell
    }

    
    // 参数 cell, indexPath 是前一个 cell 和 indexPath
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        // 获取当前显示的 indexPath
        let path = collectionView.indexPathsForVisibleItems().last!
        
        // 判断是否是末尾的 indexPath
        if path.item == imageCount - 1 {
            // 播放动画
            let cell = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell
            cell.startButtonAnim()
        }
    }
}

    
    /// 自定义cell
    //新特性cell
class NewFeatureCell: UICollectionViewCell {
    
    /// 图像索引 - 私有属性，在同一个文件中，是允许访问的！
    private var imageIndex: Int = 0 {
        didSet {
            iconview.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            startButton.hidden = true
        }
    }
    
    func startbuttonClick() {
         NSNotificationCenter.defaultCenter().postNotificationName(TWRootViewControllerSwitchNotification, object: true)
    }
    
    /// 开始按钮动画
    private func startButtonAnim() {
        startButton.hidden = false
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        // 禁用按钮操作
        startButton.userInteractionEnabled = false
        
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            
            // 恢复默认形变
            self.startButton.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                // 启用按钮点击
                self.startButton.userInteractionEnabled = true
        }
    }

        //设置UI
        override init(frame: CGRect) {
            super.init(frame: frame)
            
            prepareUI()
        }
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            
            prepareUI()
        }

        
        private func prepareUI() {
            contentView.addSubview(iconview)
            contentView.addSubview(startButton)
            
            //设置图片的自动布局
            iconview.translatesAutoresizingMaskIntoConstraints = false
            contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": iconview]))
            contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": iconview]))
            
            //设置按钮的自动布局
            startButton.translatesAutoresizingMaskIntoConstraints = false
            contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
            contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))
        }
    
    
    //懒加载图片
    private lazy var iconview = UIImageView()
    //懒加载按钮
    private lazy var startButton: UIButton = {
        
        let button = UIButton()
        
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        button.setTitle("开始体验", forState: UIControlState.Normal)
        button.sizeToFit()
        button.hidden = true
        button.addTarget(self, action: "startbuttonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
        }()

}
    /// 设置新特性布局
    private class NewFeatureLayOut: UICollectionViewFlowLayout {
    
        private override func prepareLayout() {
            
            itemSize = (collectionView?.bounds.size)!
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
            collectionView?.showsVerticalScrollIndicator = false
        }
        
    }
